/*
 *  Created on: Nov 21, 2012
 *      Author: Andrey Belomutskiy
 */

#include <string.h>
#include "rfifile.h"
#include "rficonsole.h"

FATFS fs;
FATFS *fsp;
DWORD fre_clust, fre_sect, tot_sect;

/* FS mounted and ready.*/
static bool_t fs_ready = FALSE;
/* Generic large buffer.*/
uint8_t fbuff[1024];

static void cmd_tree();

void initFileUtil() {

	addConsoleAction("tree", &cmd_tree);

	FRESULT err;

	fsp = &fs;

//	  sdStart(&SD1, NULL);
//	  sdcStart(&SDCD1, NULL);

	/*
	 * On insertion SDC initialization and FS mount.
	 */
//	if (sdcConnect(&SDCD1))
//		return;
//	err = f_mount(0, &fs);
	if (err != FR_OK) {
//		sdcDisconnect(&SDCD1);
//		return;
	}
	fs_ready = TRUE;

//	int status = disk_initialize(0);

//	print("sd status: %d\r\n", status);

	//	/* Get volume information and free clusters of drive 1 */
	//	f_getfree("1:", &fre_clust, &fs);
	//
	//	/* Get total sectors and free sectors */
	//	tot_sect = (fs->n_fatent - 2) * fs->csize;
	//	fre_sect = fre_clust * fs->csize;

}

static FRESULT scan_files(char *path) {
	FRESULT res;
	FILINFO fno;
	DIR dir;
	int i;
	char *fn;

	res = f_opendir(&dir, path);
	if (res == FR_OK) {
		i = strlen(path);
		for (;;) {
			res = f_readdir(&dir, &fno);
			if (res != FR_OK || fno.fname[0] == 0)
				break;
			if (fno.fname[0] == '.')
				continue;
			fn = fno.fname;
			if (fno.fattrib & AM_DIR) {
				path[i++] = '/';
				strcpy(&path[i], fn);
				res = scan_files(path);
				if (res != FR_OK)
					break;
				path[i] = 0;
			} else {
				print("%s/%s\r\n", path, fn);
			}
		}
	}
	return res;
}

static void cmd_tree() {
	FRESULT err;
	uint32_t clusters;

	if (!fs_ready) {
		print("File System not mounted\r\n");
		return;
	}
	err = f_getfree("/", &clusters, &fsp);
	if (err != FR_OK) {
		print("FS: f_getfree() failed\r\n");
		return;
	}
	print("FS: %lu free clusters, %lu sectors per cluster, %lu bytes free\r\n",
			clusters, (uint32_t) fs.csize,
			clusters * (uint32_t) fs.csize * (uint32_t) SDC_BLOCK_SIZE);
	fbuff[0] = 0;
	scan_files((char *) fbuff);
}

